/**
 * Copyright (C) cedarsoft GmbH.
 *
 * Licensed under the GNU General Public License version 3 (the "License")
 * with Classpath Exception; you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *         http://www.cedarsoft.org/gpl3ce
 *         (GPL 3 with Classpath Exception)
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 3 only, as
 * published by the Free Software Foundation. cedarsoft GmbH designates this
 * particular file as subject to the "Classpath" exception as provided
 * by cedarsoft GmbH in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 3 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 3 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact cedarsoft GmbH, 72810 Gomaringen, Germany,
 * or visit www.cedarsoft.com if you need additional information or
 * have any questions.
 */

package com.exadel.googleregistrator.verification;

import java.io.*;
import java.net.Socket;
import java.net.URL;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.SSLSocketFactory;

public class SpeechRecognizer {
    public static final String TARGET_HTTPS_SERVER = "www.google.com";
    public static final int TARGET_HTTPS_PORT = 443;


    public String recognizeSpeech(File speechFile) throws IOException {
        Socket socket = SSLSocketFactory.getDefault().createSocket(TARGET_HTTPS_SERVER, TARGET_HTTPS_PORT);
        try {
            String request = createRequest(18000, speechFile.length());
            sendRequest(socket, request, speechFile);
            return extractSpeech(receiveAnswer(socket));
        } finally {
            socket.close();
        }
    }

    public String recognizeSpeech(URL speechfileUrl) throws IOException {
        Socket socket = SSLSocketFactory.getDefault().createSocket(TARGET_HTTPS_SERVER, TARGET_HTTPS_PORT);
        try {
            String request = createRequest(41000, speechfileUrl.openConnection().getContentLength());
            sendRequest(socket, request, speechfileUrl);
            System.out.println("request sent");
            return extractSpeech(receiveAnswer(socket));
        } finally {
            socket.close();
        }
    }


    public String createRequest(int rate, long fileLength) {
        String request = "";
        request += "POST /speech-api/v1/recognize?xjerr=1&client=chromium&lang=ru-RU HTTP/1.1\r\n";
        request += "Host: " + TARGET_HTTPS_SERVER + "\r\n";
        request += "Content-Type: audio/x-flac; rate=" + rate + "\r\n";
        request += "Content-Length:" + fileLength + "\r\n";
        request += "\r\n";
        return request;
    }

    private void sendRequest(Socket socket, String request, File file) throws IOException {
        OutputStream out = socket.getOutputStream();
        byte[] bytes = request.getBytes("UTF-8");
        out.write(bytes, 0, bytes.length);
        InputStream fileInput = new FileInputStream(file);
        byte[] buf = new byte[1024];
        int bytesRead;
        while ((bytesRead = fileInput.read(buf)) > 0) {
            out.write(buf, 0, bytesRead);
        }
        out.flush();
    }

    private void sendRequest(Socket socket, String request, URL fileUrl) throws IOException {
        OutputStream out = socket.getOutputStream();
        byte[] bytes = request.getBytes("UTF-8");
        out.write(bytes, 0, bytes.length);
        InputStream fileInput = fileUrl.openStream();
        byte[] buf = new byte[1024];
        int bytesRead;
        while ((bytesRead = fileInput.read(buf)) > 0) {
            out.write(buf, 0, bytesRead);
        }
        out.flush();
    }

    private String receiveAnswer(Socket socket) throws IOException {
        BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream(), "UTF-8"));
        String line;
        while ((line = in.readLine()) != null) {
            if (line.contains("utterance")) {
                break;
            }
        }
        return line;
    }

    public String extractSpeech(String requestAnswer) {
        Pattern pattern = Pattern.compile("utterance\":\"(.*?)\"");
        Matcher matcher = pattern.matcher(requestAnswer);
        matcher.find();
        return matcher.group(1);
    }

    public String getVerificationCode(String voiceMessage) {
        Scanner sc = new Scanner(voiceMessage);
        String code = "";
        while (sc.hasNext()) {
            if (sc.hasNextInt()) {
                code += sc.nextInt();
            } else {
                sc.next();
            }
        }
        code = code.substring(code.length() - 6);
        return code;
    }

    public static void main(String[] args) {
        SpeechRecognizer sr = new SpeechRecognizer();
        try {
            String speech = sr.recognizeSpeech(new File("C:\\Temp\\temp.flac"));
            System.out.println(speech);
            System.out.println(sr.getVerificationCode(speech));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

